package cn.yyx.financeservice.controller;


import cn.yyx.common.R;
import cn.yyx.empservice.entity.attendance.Attendance;
import cn.yyx.empservice.entity.employee.Employee;
import cn.yyx.empservice.service.AttendanceService;
import cn.yyx.empservice.service.EmployeeService;
import cn.yyx.financeservice.entity.Finance;
import cn.yyx.financeservice.entity.Query;
import cn.yyx.financeservice.service.FinanceService;
import cn.yyx.orderservice.entity.Order;
import cn.yyx.orderservice.entity.PerformanceStep;
import cn.yyx.orderservice.service.OrderService;
import cn.yyx.orderservice.service.PerformanceStepService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author sun
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/finance")
public class FinanceController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private PerformanceStepService performanceStepService;
    @Autowired
    private FinanceService financeService;
    /**
     * 获取雇员名字
     * @return
     */
    @GetMapping("ord")
    public R getOrder(){
        List<Employee> employeeList = employeeService.list();
        return R.ok().data("ord",employeeList);
    }
    /**
     * 添加支出
     * @param finance
     * @return
     */
    @PostMapping("add")
    public R addFinance(@RequestBody Finance finance){
        boolean save = financeService.save(finance);
        return save?R.ok().code(20000).data("items","保存成功"):R.error().code(20001).data("items","保存失败");
    }
    /**
     * 支出列表
     * @param amount
     * @param start
     * @param end
     * @return
     */
    @GetMapping("list")
    public R getList( String amount,String start , String end){
        Page<Finance> page = new Page<>();
        if(start!=null&&end!=null) {
            QueryWrapper<Finance> financeQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Finance> wrapper = financeQueryWrapper.between("pay_date", start, end);
            List<Finance> finances = financeService.list(wrapper);
            financeService.page(page, wrapper);
            double sum=0;
            for (Finance money : finances) {
                double num= Double.parseDouble(money.getAmount());
                sum+=num;
            }
            System.out.println("sum"+sum);
            return R.ok().data("items", finances).data("total", page.getTotal()).data("sum",sum);
        }
        if(amount!=null&&!amount.equals("")){
            QueryWrapper<Finance> financeQueryWrapper = new QueryWrapper<>();
            financeQueryWrapper.eq("operator_id",amount);
            List<Finance> list = financeService.list(financeQueryWrapper);
            double sum=0;
            for (Finance money : list) {
                double num= Double.parseDouble(money.getAmount());
                sum+=num;
            }
            return R.ok().data("items", list).data("total", page.getTotal()).data("sum",sum);
        }
            financeService.page(page);
            List<Finance> finances = financeService.list();
        double sum=0;
        for (Finance money : finances) {
            double num= Double.parseDouble(money.getAmount());
            sum+=num;
        }
        return R.ok().data("items", finances).data("total", page.getTotal()).data("sum",sum);
    }


     /**
     * 薪资管理
     * @param query
     * @return
     */
    @PostMapping("sal/list")
    public R getSalList(@RequestBody Query query){
        List<Map>  objects=new ArrayList();
        List<Employee> employeeList = employeeService.list();
        String name = "null";
        Double sal = 0.0;
        String phone = null;
        String job = null;

        for (Employee employee : employeeList) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("sale_id", employee.getId()).or().eq("operator_id", employee.getId());
            List<Order> orderList = orderService.list(orderQueryWrapper);
            if(orderList.isEmpty()){
                QueryWrapper<Attendance> attendanceQueryWrapper = new QueryWrapper<>();
                attendanceQueryWrapper.eq("emp_id",employee.getId());
                List<Attendance> attendanceList = attendanceService.list(attendanceQueryWrapper);
                double leaveDay=0.0;
                if(attendanceList!=null){
                    int year=0;
                    int month=0;
                    for (Attendance attendance : attendanceList) {
                        Date leaveTime = attendance.getLeaveTime();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                        String formattedDate = sdf.format(leaveTime);
                        if(year==0&&month==0){
                            year = Integer.parseInt(formattedDate.substring(0, 4));
                            month = Integer.parseInt(formattedDate.substring(5));
                            leaveDay=attendance.getLeaveDay();
                        }else{
                            int year1 = Integer.parseInt(formattedDate.substring(0, 4));

                            int month1 = Integer.parseInt(formattedDate.substring(5));
                            if(year==year1&&month==month1){
                                leaveDay+=attendance.getLeaveDay();
                            }
                        }
                    }
                }
                Map  map=new HashMap();
                map.put("leaveDay",leaveDay);
                name = employee.getName();
                sal = employee.getSal();
                phone = employee.getPhone();
                job = employee.getJob();
                map.put("name", name);
                map.put("phone", phone);
                map.put("job", job);
                map.put("sal", sal);
                map.put("totalSal",sal);
                objects.add(map);
            }

        }
        for (Employee employee : employeeList) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("sale_id", employee.getId());
            List<Order> orderList = orderService.list(orderQueryWrapper);
            if (!orderList.isEmpty()) {
                QueryWrapper<Attendance> attendanceQueryWrapper = new QueryWrapper<>();
                attendanceQueryWrapper.eq("emp_id",employee.getId());
                List<Attendance> attendanceList = attendanceService.list(attendanceQueryWrapper);
                double leaveDay=0.0;
                if(attendanceList!=null){
                    int year=0;
                    int month=0;
                    for (Attendance attendance : attendanceList) {
                        Date leaveTime = attendance.getLeaveTime();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                        String formattedDate = sdf.format(leaveTime);
                        if(year==0&&month==0){
                            year = Integer.parseInt(formattedDate.substring(0, 4));
                            month = Integer.parseInt(formattedDate.substring(5));
                            leaveDay=attendance.getLeaveDay();
                        }else{
                            int year1 = Integer.parseInt(formattedDate.substring(0, 4));

                            int month1 = Integer.parseInt(formattedDate.substring(5));
                            if(year==year1&&month==month1){
                                leaveDay+=attendance.getLeaveDay();
                            }
                        }
                    }
                }
                Map  map=new HashMap();
                map.put("leaveDay",leaveDay);
                map.put("saleCommission",new BigDecimal("0"));
                map.put("salePerformance",new BigDecimal("0"));
                for (Order order : orderList) {
                    BigDecimal orderPrice = order.getOrderPrice();
                    System.out.println("dsngfjkhgjkdhsgjdsgsd" + orderPrice);
                    QueryWrapper<PerformanceStep> performanceStepQueryWrapper = new QueryWrapper<>();
                    List<PerformanceStep> performanceStepList = performanceStepService.list(performanceStepQueryWrapper);
                    System.out.println(performanceStepList);
                    performanceStepList.forEach(performanceStep -> {
                        if (orderPrice.compareTo(new BigDecimal(performanceStep.getLowlimit())) > -1 && orderPrice.compareTo(new BigDecimal(performanceStep.getUplimit())) < 1) {
                            BigDecimal saleCommission = (BigDecimal) map.get("saleCommission");
                            System.out.println(performanceStep);
                            BigDecimal multiply = (orderPrice.multiply(new BigDecimal(performanceStep.getSaleCommission()))).setScale(2, BigDecimal.ROUND_DOWN);
                            map.put("saleCommission", saleCommission.add(multiply));
                        }
                    });
                    BigDecimal salePerformance = (BigDecimal) map.get("salePerformance");
                    map.put("salePerformance", salePerformance.add(orderPrice));
                    name = employee.getName();
                    sal = employee.getSal();
                    phone = employee.getPhone();
                    job = employee.getJob();
                    map.put("name", name);
                    map.put("phone", phone);
                    map.put("job", job);
                    map.put("sal", sal);
                   double v = sal / 22;
                    BigDecimal bigDecimal = new BigDecimal(v).setScale(2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal bigDecimal1 = new BigDecimal(22 - leaveDay);
                    BigDecimal multiply = bigDecimal1.multiply(bigDecimal);
                    BigDecimal o = (BigDecimal)map.get("salePerformance");
                    BigDecimal techCommission = multiply.add(o);
                    map.put("totalSal",techCommission);
                }
                objects.add(map);
            }
        }
        for (Employee employee : employeeList) {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("operator_id", employee.getId());
            List<Order> orderList = orderService.list(orderQueryWrapper);
            if (!orderList.isEmpty()) {
                QueryWrapper<Attendance> attendanceQueryWrapper = new QueryWrapper<>();
                attendanceQueryWrapper.eq("emp_id",employee.getId());
                List<Attendance> attendanceList = attendanceService.list(attendanceQueryWrapper);
                double leaveDay=0.0;
                if(attendanceList!=null){
                    int year=0;
                    int month=0;
                    for (Attendance attendance : attendanceList) {
                        Date leaveTime = attendance.getLeaveTime();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                        String formattedDate = sdf.format(leaveTime);
                        if(year==0&&month==0){
                            year = Integer.parseInt(formattedDate.substring(0, 4));
                            month = Integer.parseInt(formattedDate.substring(5));
                            leaveDay=attendance.getLeaveDay();
                        }else{
                            int year1 = Integer.parseInt(formattedDate.substring(0, 4));

                            int month1 = Integer.parseInt(formattedDate.substring(5));
                            if(year==year1&&month==month1){
                                leaveDay+=attendance.getLeaveDay();
                            }
                        }
                    }
                }
                Map  map=new HashMap();
                map.put("leaveDay",leaveDay);
                map.put("techCommission",new BigDecimal("0"));
                map.put("techPerformance",new BigDecimal("0"));
                int teachOparetionRecords=0;
                for (Order order : orderList) {
                    teachOparetionRecords++;
                    BigDecimal orderPrice = order.getOrderPrice();
                    System.out.println("dsngfjkhgjkdhsgjdsgsd" + orderPrice);
                    QueryWrapper<PerformanceStep> performanceStepQueryWrapper = new QueryWrapper<>();
                    List<PerformanceStep> performanceStepList = performanceStepService.list(performanceStepQueryWrapper);
                    System.out.println(performanceStepList);
                    performanceStepList.forEach(performanceStep -> {
                        if (orderPrice.compareTo(new BigDecimal(performanceStep.getLowlimit())) > -1 && orderPrice.compareTo(new BigDecimal(performanceStep.getUplimit())) < 1) {
                            System.out.println("奥附件哦按段金佛啊");
                            BigDecimal saleCommission = (BigDecimal) map.get("techCommission");
                            System.out.println(performanceStep);
                            BigDecimal multiply = (orderPrice.multiply(new BigDecimal(performanceStep.getSaleCommission()))).setScale(2, BigDecimal.ROUND_DOWN);
                            System.out.println("fdfhdsjihfihf:  " + multiply);
                            map.put("techCommission", saleCommission.add(multiply));
                        }
                    });
                    BigDecimal salePerformance = (BigDecimal) map.get("techPerformance");
                    map.put("techPerformance", salePerformance.add(orderPrice));
                    name = employee.getName();
                    sal = employee.getSal();
                    phone = employee.getPhone();
                    job = employee.getJob();
                    map.put("name", name);
                    map.put("phone", phone);
                    map.put("job", job);
                    map.put("sal", sal);
                    map.put("teachOparetionRecords",teachOparetionRecords);
                    double v = sal / 22;
                    BigDecimal bigDecimal = new BigDecimal(v).setScale(2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal bigDecimal1 = new BigDecimal(22 - leaveDay);
                    BigDecimal multiply = bigDecimal1.multiply(bigDecimal);
                    BigDecimal o = (BigDecimal)map.get("techCommission");
                    BigDecimal techCommission = multiply.add(o);
                    map.put("totalSal",techCommission);
                }
                objects.add(map);
            }
        }
            if (!query.getName().equals("")) {
                ArrayList<Object> objects1 = new ArrayList<>();
                objects.forEach(map -> {
                    if (map.get("name").equals(query.getName())) {
                        objects1.add(map);
                    }
                });
                return R.ok().data("items", objects1);
            }
            if (!query.getBegin().equals("") && !query.getEnd().equals("")) {
                ArrayList<Object> objects1 = new ArrayList<>();
                objects.forEach(map -> {
                    QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
                    employeeQueryWrapper.eq("name", map.get("name"));
                    List<Employee> employeeList1 = employeeService.list(employeeQueryWrapper);
                    employeeList1.forEach(employee -> {
                        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
                        orderQueryWrapper.between("order_date", query.getBegin(),query.getEnd());
                        List<Order> orderList = orderService.list(orderQueryWrapper);
                        if (!orderList.isEmpty()) {
                            objects1.add(map);
                        }
                    });
                });
                return R.ok().data("items", objects1);
            }
        return R.ok().data("items",objects);
    }

}

